<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/python/函数/">
  <title>
    
      python基础 &gt; 函数 - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#python" title="python">python</a>
              
              <a class="tag" href="/tags/#基础" title="基础">基础</a>
              
            </div>
            <h1>python基础 &gt; 函数</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2020-11-11
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">10</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">2.5k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <h2 id="1-定义一个函数"><a href="#1-定义一个函数" class="headerlink" title="1. 定义一个函数"></a>1. 定义一个函数</h2><p>函数包括函数头和函数体。函数头以<code>def</code>关键字开始，后面紧接着函数名以及形参并以冒号结束。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">max</span>(<span class="params">num1, num2</span>):</span></span><br><span class="line">    <span class="keyword">if</span> num1 &gt; num2:</span><br><span class="line">        result = num1</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        result = num2</span><br><span class="line">    <span class="keyword">return</span> result</span><br></pre></td></tr></table></figure>
<p>注意的问题：</p>
<ul>
<li>函数形参不需要申明其类型，也不需要指定函数的返回值类型</li>
<li>即时该函数不需要接收任何参数，也必须保留一对空的括号</li>
<li>括号后面的冒号必不可少</li>
<li>函数体相对于<code>def</code>关键字必须保持一定的空格缩进</li>
<li>函数返回值类型与return语句返回表达式的类型一致</li>
</ul>
<h2 id="2-调用一个函数"><a href="#2-调用一个函数" class="headerlink" title="2. 调用一个函数"></a>2. 调用一个函数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">max</span>(<span class="params">num1, num2</span>):</span></span><br><span class="line">    <span class="keyword">if</span> num1 &gt; num2:</span><br><span class="line">        result = num1</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        result = num2</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span>():</span></span><br><span class="line">    i = <span class="number">5</span></span><br><span class="line">    j = <span class="number">2</span></span><br><span class="line">    k = <span class="built_in">max</span>(<span class="number">4</span>,<span class="number">5</span>)   <span class="comment">#调用max函数</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;The Larger number of&quot;</span>,i, <span class="string">&quot;and&quot;</span>, j, <span class="string">&quot;is&quot;</span>, k)</span><br><span class="line">main()  <span class="comment">#调用main函数</span></span><br><span class="line"><span class="comment">#The Larger number of 5 and 2 is 5</span></span><br></pre></td></tr></table></figure>
<p><img src="image-20201111221540945.png" alt="image-20201111221540945"></p>
<blockquote>
<p>函数在内存中被调用，函数可以定义在脚本文件的任意位置</p>
</blockquote>
<h2 id="3-通过传引用来传递参数"><a href="#3-通过传引用来传递参数" class="headerlink" title="3. 通过传引用来传递参数"></a>3. 通过传引用来传递参数</h2><p>当调用带参数的函数时，每个实参的引用值被传递给函数的形参</p>
<p>如果是实参是一个数字或一个字符串，函数中的形参有没有变化，实参是不受影响的，<strong><em>因为数字和字符串被称为不可变对象</em></strong>，当你将一个新数字赋值给变量时，Python会为这个新数字创建新对象，然后将这个新对象的引用赋值给这个变量。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span>(<span class="params">x</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(x))   <span class="comment">#140714756544160</span></span><br><span class="line">    x += <span class="number">1</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(x))   <span class="comment">#140714756544160</span></span><br><span class="line"></span><br><span class="line">n = <span class="number">1</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(n))    <span class="comment">#140714756544192</span></span><br><span class="line">test(n)</span><br></pre></td></tr></table></figure>
<p><img src="image-20201116191359788.png" alt="image-20201116191359788"></p>
<p>如果传递给函数的是列表、字典、集合或其他自定义的可变序列，并且在函数内部使用下标或序列自身支持的方式为可变序列增加，删除元素或修改元素值时，修改后的结果是可以反映到函数之外的。</p>
<h2 id="4-函数参数"><a href="#4-函数参数" class="headerlink" title="4. 函数参数"></a>4. 函数参数</h2><h3 id="4-1-位置参数"><a href="#4-1-位置参数" class="headerlink" title="4.1 位置参数"></a>4.1 位置参数</h3><p>调用函数时实参和形参的顺序严格一致，并且实参和形参的数量必须相同</p>
<h3 id="4-2-默认参数"><a href="#4-2-默认参数" class="headerlink" title="4.2 默认参数"></a>4.2 默认参数</h3><ul>
<li>Python允许定义带默认参数值的函数</li>
<li>可以混用默认值参数和非默认值参数，非默认值参数必须定义在默认值参数之前</li>
<li>多次调用函数并且不为默认值参数传递值时，默认值参数只在定义时进行一次解释和初始化</li>
<li>要避免使用列表、字典、集合或其他可变序列作为函数参数默认值</li>
<li>函数的默认值参数是在函数定义时确定值的</li>
</ul>
<h3 id="4-3-关键参数"><a href="#4-3-关键参数" class="headerlink" title="4.3 关键参数"></a>4.3 关键参数</h3><p>通过关键参数可以按参数名字传递值，明确指定哪个值传递给哪个参数，实参顺序和形参顺序不一致</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>(<span class="params">a, b, c</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line"></span><br><span class="line">demo(b = <span class="number">2</span>, c = <span class="number">0</span>, a = <span class="number">4</span>) <span class="comment">#4 2 0</span></span><br></pre></td></tr></table></figure>
<h3 id="4-4-可变长度参数"><a href="#4-4-可变长度参数" class="headerlink" title="4.4 可变长度参数"></a>4.4 可变长度参数</h3><p>可变长度参数有两种形式：</p>
<p>*parameter：用来接收任意多个实参并将其放在一个元组中</p>
<p>**parameter：后者类似于关键参数一样显式赋值形式的多个实参并将其放入字典中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>(<span class="params">*p</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(p)   </span><br><span class="line">demo(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>)   <span class="comment">#(1, 2, 3)</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo1</span>(<span class="params">**p</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(p)</span><br><span class="line">demo1(a = <span class="number">1</span>, b = <span class="number">2</span>, c = <span class="number">3</span>)  <span class="comment">#&#123;&#x27;a&#x27;: 1, &#x27;b&#x27;: 2, &#x27;c&#x27;: 3&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="4-5-传递参数时的序列解包"><a href="#4-5-传递参数时的序列解包" class="headerlink" title="4.5 传递参数时的序列解包"></a>4.5 传递参数时的序列解包</h3><p>与可变长度的参数相反，这里的序列解包是指实参，也有两种形式：</p>
<p>*parameter:可对列表、元组、集合、字典以及可迭代对象作为实参，进行解包，把序列中的值传递给多个单变量形参；</p>
<ul>
<li>针对字典中*dict是对字典的键进行解包</li>
<li>*dict.values()是对字典的值进行解包</li>
</ul>
<p>**parameter：可字典进行解包，把字典转换为类似于关键参数的形式进行参数传递。</p>
<ul>
<li>实参字典中所有的键必须是函数的形参名字</li>
<li>函数中两个星号的可变长度参数相对应</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">p = &#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>,<span class="string">&#x27;b&#x27;</span>:<span class="number">2</span>,<span class="string">&#x27;c&#x27;</span>:<span class="number">3</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>(<span class="params">a,b,c</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line"></span><br><span class="line">f(**p)  <span class="comment">#1 2 3</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>(<span class="params">**p</span>):</span></span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> p.items():</span><br><span class="line">        <span class="built_in">print</span>(item)</span><br><span class="line">demo(**p)</span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">(&#x27;a&#x27;, 1)</span></span><br><span class="line"><span class="string">(&#x27;b&#x27;, 2)</span></span><br><span class="line"><span class="string">(&#x27;c&#x27;, 3)</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<p>一个函数多种形式接受数据：</p>
<p>位置参数-&gt; 默认值参数 -&gt; <em>parameter -&gt; *</em>parameter</p>
<p>调用函数也是这个顺序</p>
<ul>
<li>实参使用一个<em>，会被当作位置参数对待，并且会在关键参数和使用*</em>解包，之前进行处理。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>(<span class="params">a, b, c</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line"></span><br><span class="line">demo(*(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>))   <span class="comment">#1 2 3</span></span><br><span class="line">demo(<span class="number">1</span>,*(<span class="number">2</span>,<span class="number">3</span>))   <span class="comment">#1 2 3</span></span><br><span class="line">demo(<span class="number">1</span>,*(<span class="number">2</span>,),<span class="number">3</span>)  <span class="comment">#1 2 3</span></span><br><span class="line">demo(<span class="number">1</span>,<span class="number">2</span>,*(<span class="number">3</span>,))  <span class="comment">#1 2 3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#一个星号的序列解包相当于位置参数</span></span><br><span class="line"><span class="comment">#demo(a = 1,*(2, 3)) #TypeError: demo() got multiple values for argument &#x27;a&#x27;</span></span><br><span class="line"><span class="comment">#demo(b = 1,*(2, 3)) #TypeError: demo() got multiple values for argument &#x27;b&#x27;</span></span><br><span class="line">demo(c = <span class="number">1</span>,*(<span class="number">2</span>, <span class="number">3</span>)) <span class="comment"># 2 3 1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#序列解包不能再关键参数解包之后</span></span><br><span class="line"><span class="comment">#demo(**&#123;&#x27;a&#x27;:1,&#x27;b&#x27;:2&#125;,*(3,))  #iterable argument unpacking follows keyword argument unpacking</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#一个星号的序列解包相当于位置参数</span></span><br><span class="line"><span class="comment">#demo(*(3,),**&#123;&#x27;a&#x27;:1,&#x27;b&#x27;:2&#125;)  #demo() got multiple values for argument &#x27;a&#x27;</span></span><br><span class="line"> </span><br><span class="line">demo(*(<span class="number">3</span>,), **&#123;<span class="string">&#x27;c&#x27;</span>:<span class="number">1</span>,<span class="string">&#x27;b&#x27;</span>:<span class="number">2</span>&#125;)  <span class="comment">#3 2 1</span></span><br></pre></td></tr></table></figure>
<h2 id="5-返回多个值"><a href="#5-返回多个值" class="headerlink" title="5. 返回多个值"></a>5. 返回多个值</h2><p>Python的return语句可以返回多个值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sort</span>(<span class="params">number1, number2</span>):</span></span><br><span class="line">    <span class="keyword">if</span>(number1 &gt; number2):</span><br><span class="line">        <span class="keyword">return</span> number1,number2</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> number2,number1</span><br><span class="line"></span><br><span class="line">n1, n2 = sort(<span class="number">3</span>,<span class="number">4</span>)</span><br><span class="line"><span class="built_in">print</span>(n1,n2)</span><br></pre></td></tr></table></figure>
<h2 id="6-变量作用域"><a href="#6-变量作用域" class="headerlink" title="6. 变量作用域"></a>6. 变量作用域</h2><p>在函数内定义的局部变量只在该函数内可见</p>
<p>在函数内部使用<code>global</code>定义的全局变量当函数结束以后仍然存在并且可以访问。</p>
<p>函数内部通过<code>global</code>来声明或定义全局变量，有两种情况：</p>
<ul>
<li>一个变量已在函数外定义，如果在函数内需要修改这个变量的值，并将修改的结果反映到函数之外，可以在函数内用关键字global明确声明要使用已定义的同名全局变量。</li>
<li>在函数内部直接使用<code>global</code>关键字将一个变量声明为全局变量，如果在函数外没有定义该全局变量，在调用函数之后，会创建新的全局变量<ul>
<li>函数内只引用变量而没有赋值，该变量为（隐式的）全局变量</li>
<li>函数内某条代码为变量赋值操作，该变量为（隐式的）局部变量，除非在函数能赋值操作之前显示地用<code>global</code>进行声明</li>
</ul>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>():</span></span><br><span class="line">    <span class="keyword">global</span> x</span><br><span class="line">    x = <span class="number">3</span></span><br><span class="line">    y = <span class="number">4</span></span><br><span class="line">    <span class="built_in">print</span>(x,y)   </span><br><span class="line">x = <span class="number">5</span></span><br><span class="line">demo()    <span class="comment">#3 4</span></span><br><span class="line"><span class="built_in">print</span>(x)  <span class="comment">#3</span></span><br><span class="line"><span class="built_in">print</span>(y)  <span class="comment">#NameError: name &#x27;y&#x27; is not defined</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">10</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo1</span>():</span></span><br><span class="line">    <span class="built_in">print</span>(a)   <span class="comment">#语句引发异常，因为a变量现在不存在</span></span><br><span class="line">    <span class="comment">#UnboundLocalError: local variable &#x27;a&#x27; referenced before assignment</span></span><br><span class="line">    a += <span class="number">10</span>    <span class="comment">#赋值语句，x被认为该作用域内隐式的局部变量</span></span><br><span class="line">    <span class="built_in">print</span>(a)</span><br><span class="line">demo1()</span><br></pre></td></tr></table></figure>
<h2 id="7-lambda表达式"><a href="#7-lambda表达式" class="headerlink" title="7. lambda表达式"></a>7. lambda表达式</h2><p>lambda表达式声明匿名函数</p>
<p>应用场景：类似于函数的功能但又不想定义函数的场合</p>
<p>注意事项：</p>
<ul>
<li>lambda表达式只可以包含一个表达式，不允许包含其他复杂的语句；</li>
<li>表达式中可以调用其他函数，该表达式的计算结果相当于函数的返回值</li>
<li>可以给lambda表达式起名字</li>
<li>支持默认值参数</li>
<li>可以作为函数的参数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">f = <span class="keyword">lambda</span> x, y,z : x + y +z  <span class="comment">#给lambda表达式起名字</span></span><br><span class="line"><span class="built_in">print</span>(f(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>))   <span class="comment">#6</span></span><br><span class="line"></span><br><span class="line">g = <span class="keyword">lambda</span> x, y = <span class="number">2</span>, z = <span class="number">3</span>: x + y + z  <span class="comment">#支持默认值参数</span></span><br><span class="line"><span class="built_in">print</span>(g(<span class="number">1</span>))  <span class="comment">#6</span></span><br><span class="line"></span><br><span class="line">l = [(<span class="keyword">lambda</span> x: x ** <span class="number">2</span>), (<span class="keyword">lambda</span> x: x ** <span class="number">3</span>),(<span class="keyword">lambda</span> x: x ** <span class="number">4</span>)]</span><br><span class="line"><span class="built_in">print</span>(l[<span class="number">0</span>](<span class="number">2</span>),l[<span class="number">1</span>](<span class="number">2</span>),l[<span class="number">2</span>](<span class="number">2</span>))  <span class="comment">#4 8 16</span></span><br><span class="line"></span><br><span class="line">d = &#123;<span class="string">&#x27;f1&#x27;</span>:(<span class="keyword">lambda</span>: <span class="number">2</span> + <span class="number">3</span>),<span class="string">&#x27;f2&#x27;</span>:(<span class="keyword">lambda</span>: <span class="number">2</span> * <span class="number">3</span>),<span class="string">&#x27;f3&#x27;</span>:(<span class="keyword">lambda</span>: <span class="number">2</span> ** <span class="number">3</span>)&#125;</span><br><span class="line"><span class="built_in">print</span>(d[<span class="string">&#x27;f1&#x27;</span>](),d[<span class="string">&#x27;f2&#x27;</span>](), d[<span class="string">&#x27;f3&#x27;</span>]())  <span class="comment">#5 6 8</span></span><br><span class="line"></span><br><span class="line">l = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> x:x + <span class="number">10</span>,l)))  <span class="comment">#[11, 12, 13, 14, 15, 16]</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>(<span class="params">n</span>):</span></span><br><span class="line">    <span class="keyword">return</span> n*n</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> x: demo(x),l)))   <span class="comment">#在lambda中调用其他函数  [1, 4, 9, 16, 25, 36]</span></span><br><span class="line"></span><br><span class="line">l.sort(key=<span class="keyword">lambda</span> x:x,reverse=<span class="literal">True</span>)  <span class="comment">#用在列表的sort()方法中，作为函数参数</span></span><br><span class="line"><span class="built_in">print</span>(l)  <span class="comment">#[6, 5, 4, 3, 2, 1]</span></span><br></pre></td></tr></table></figure>
<p>lambda表达式中注意变量作用域的问题：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">r = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">    r.append(<span class="keyword">lambda</span> : i ** <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(r[<span class="number">1</span>]())  <span class="comment">#81</span></span><br><span class="line"><span class="built_in">print</span>(r[<span class="number">2</span>]())  <span class="comment">#81</span></span><br><span class="line"></span><br><span class="line">r = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">    r.append(<span class="keyword">lambda</span> n = i: n ** <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(r[<span class="number">1</span>]())  <span class="comment">#1</span></span><br><span class="line"><span class="built_in">print</span>(r[<span class="number">2</span>]())  <span class="comment">#4</span></span><br></pre></td></tr></table></figure>
<h2 id="8-函数嵌套"><a href="#8-函数嵌套" class="headerlink" title="8. 函数嵌套"></a>8. 函数嵌套</h2><p>Python允许函数的嵌套定义</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linear</span>(<span class="params">a,b</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">result</span>(<span class="params">x</span>):</span></span><br><span class="line">        <span class="keyword">return</span> a + b + x</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(linear(<span class="number">2</span>,<span class="number">3</span>)(<span class="number">3</span>))</span><br><span class="line"></span><br><span class="line">f = linear(<span class="number">2</span>,<span class="number">2</span>)</span><br><span class="line"><span class="built_in">print</span>(f(<span class="number">4</span>))</span><br></pre></td></tr></table></figure>
<h2 id="9-可调用对象"><a href="#9-可调用对象" class="headerlink" title="9. 可调用对象"></a>9. 可调用对象</h2><p>函数属于Python可调用对象之一，类也是可调用的，构造方法的存在，像list()、tuple()、dict()实际上是调用类的构造方法。</p>
<p>任何包含<code>__call__()</code>方法的类的对象也是可调用的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">linear</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,a,b</span>):</span></span><br><span class="line">        self.a,self.b = a,b</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span>(<span class="params">self,x</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.a + self.b + x</span><br><span class="line"></span><br><span class="line">f = linear(<span class="number">2</span>,<span class="number">2</span>)</span><br><span class="line"><span class="built_in">print</span>(f(<span class="number">4</span>))</span><br></pre></td></tr></table></figure>
<h2 id="10-修饰器"><a href="#10-修饰器" class="headerlink" title="10. 修饰器"></a>10. 修饰器</h2><p>修饰器本质也是一个函数，这个函数接收其他函数作为参数并对其进行一定的改造之后返回新函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">before</span>(<span class="params">func</span>):</span>   <span class="comment">#定义修饰器</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span>(<span class="params">*args,**kwargs</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Before function called&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> func(*args,**kwargs)</span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">after</span>(<span class="params">func</span>):</span>  <span class="comment">#定义修饰器</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span>(<span class="params">*args,**kwargs</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;After function called&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> func(*args,**kwargs)</span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="meta">@before</span></span><br><span class="line"><span class="meta">@after</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">demo</span>():</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;Demo function called&#x27;</span>)</span><br><span class="line"></span><br><span class="line">demo()</span><br></pre></td></tr></table></figure>
<h2 id="11-生成器函数"><a href="#11-生成器函数" class="headerlink" title="11.生成器函数"></a>11.生成器函数</h2><p>包好<code>yield</code>语句的函数可以用来创建生成器，这要的函数称为生成器函数。</p>
<p>执行到<code>yield</code>语句并返回一个值之后会暂停或挂起后面代码的执行，下次通过生成器d对象的<code>__next__()</code>方法、内置函数next()、for循环遍历生成器对象元素等显式索要数据时恢复执行</p>
<p>生成器具有<strong><em>惰性求值</em></strong>的特点</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>():</span></span><br><span class="line">    a,b = <span class="number">1</span>,<span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        <span class="keyword">yield</span> a</span><br><span class="line">        a,b = b,a + b</span><br><span class="line"></span><br><span class="line">a = f()  <span class="comment">#创建生成器对象</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> item <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">    <span class="built_in">print</span>(a.__next__(),end=<span class="string">&#x27;  &#x27;</span>)  <span class="comment">#1  1  2  3  5  8  13  21  34  55</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#使用内置函数获取中的元素</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;next()函数：&#x27;</span>,<span class="built_in">next</span>(a))  <span class="comment">#1 2 3</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">gen</span>():</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="number">2</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="number">3</span></span><br><span class="line"></span><br><span class="line">x,y,z = gen()   <span class="comment">#生成器对象支持序列解包</span></span><br><span class="line"><span class="built_in">print</span>(x,y,z)   <span class="comment">#1 2 3</span></span><br></pre></td></tr></table></figure>

        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/python/面向对象程序设计/" data-toggle="tooltip" data-placement="top" title="python基础 > 面向对象程序设计">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/spring/SpringSecurity入门/" data-toggle="tooltip" data-placement="top" title="SpringSecurity入门">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">1. 定义一个函数</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-%E8%B0%83%E7%94%A8%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">2. 调用一个函数</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-%E9%80%9A%E8%BF%87%E4%BC%A0%E5%BC%95%E7%94%A8%E6%9D%A5%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">3. 通过传引用来传递参数</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">4. 函数参数</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-1-%E4%BD%8D%E7%BD%AE%E5%8F%82%E6%95%B0"><span class="toc-nav-number">4.1.</span> <span class="toc-nav-text">4.1 位置参数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-2-%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B0"><span class="toc-nav-number">4.2.</span> <span class="toc-nav-text">4.2 默认参数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-3-%E5%85%B3%E9%94%AE%E5%8F%82%E6%95%B0"><span class="toc-nav-number">4.3.</span> <span class="toc-nav-text">4.3 关键参数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-4-%E5%8F%AF%E5%8F%98%E9%95%BF%E5%BA%A6%E5%8F%82%E6%95%B0"><span class="toc-nav-number">4.4.</span> <span class="toc-nav-text">4.4 可变长度参数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-5-%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0%E6%97%B6%E7%9A%84%E5%BA%8F%E5%88%97%E8%A7%A3%E5%8C%85"><span class="toc-nav-number">4.5.</span> <span class="toc-nav-text">4.5 传递参数时的序列解包</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#5-%E8%BF%94%E5%9B%9E%E5%A4%9A%E4%B8%AA%E5%80%BC"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">5. 返回多个值</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#6-%E5%8F%98%E9%87%8F%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-nav-number">6.</span> <span class="toc-nav-text">6. 变量作用域</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#7-lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-nav-number">7.</span> <span class="toc-nav-text">7. lambda表达式</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#8-%E5%87%BD%E6%95%B0%E5%B5%8C%E5%A5%97"><span class="toc-nav-number">8.</span> <span class="toc-nav-text">8. 函数嵌套</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#9-%E5%8F%AF%E8%B0%83%E7%94%A8%E5%AF%B9%E8%B1%A1"><span class="toc-nav-number">9.</span> <span class="toc-nav-text">9. 可调用对象</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#10-%E4%BF%AE%E9%A5%B0%E5%99%A8"><span class="toc-nav-number">10.</span> <span class="toc-nav-text">10. 修饰器</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#11-%E7%94%9F%E6%88%90%E5%99%A8%E5%87%BD%E6%95%B0"><span class="toc-nav-number">11.</span> <span class="toc-nav-text">11.生成器函数</span></a></li></ol>
        
        </div>
      </aside>
    



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#python" title="python">python</a>
            
            <a class="tag" href="/tags/#基础" title="基础">基础</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
